<template>
	<el-dialog class="abow-dialog" :visible.sync="visible" top="2vh" :lock-scroll="false"
		:title="!dataId ? '新增推广' : '编辑推广'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="650px" @close="closeFn">
		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="130px" size="medium" :inline="false"
			labelSuffix="：">
			<el-form-item prop="name" label="链接名称" size="medium">
				<el-input clearable v-model="dataForm.name" placeholder="链接名称" />
			</el-form-item>
			<el-form-item prop="spread_platform_id" label="投放平台" size="medium">
				<el-select clearable v-model="dataForm.spread_platform_id" :disabled="dataId?true:false" @change="selectSpread" placeholder="请选择" @focus="getPlatformFn">
					<el-option v-for="(item,index) in platformId" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="applet_id" v-if="dataForm.spread_platform_id" label="选择小程序" size="medium">
				<el-select clearable v-model="dataForm.applet_id" :disabled="dataId?true:false" placeholder="请选择" @focus="getAppletFn"  @change="getPlayletFn">
					<el-option v-for="(item,index) in appletList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
				</el-select>
			</el-form-item>
			<template v-if="noPlaylet">
				<div class="el-form-item__error" style="left: 160px;">
					您所选择的小程序没有短剧
				</div>
			</template>
			<template v-if="dataForm.applet_id&&!noPlaylet">
				<!-- <el-form-item prop="user_type" label="用户类型" size="medium">
					<div class="d-flex flex-row">
						<el-select class="d-flex w-50" v-model="dataForm.user_type" :disabled="dataId?true:false" placeholder="请选择用户类型" @change="episodeFn">
							<el-option v-for="(item,index) in userType" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
					</div>
				</el-form-item> -->
			
				<el-form-item v-if="diytype == 2" prop="operation_mode" label="模式">
					<el-radio-group v-model="dataForm.operation_mode" :disabled="dataId?true:false">
						<el-radio :label="1">付费模式</el-radio>
						<el-radio :label="2">IAA模式</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item  label="广告账户ID">
					<el-input style="width: 50%;" clearable v-model="dataForm.ad_account" :disabled="dataId && diyad_account!=''" placeholder="广告账户ID" />
				</el-form-item>
				<el-form-item prop="playlet_id" label="推广短剧" size="medium">
					<div class="d-flex flex-row">
						<el-select class="d-flex w-50" clearable v-model="dataForm.playlet_id" :disabled="dataId?true:false" placeholder="请选择推广短剧" @change="episodeFn(false)">
							<el-option v-for="(item,index) in playletList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
					</div>
				</el-form-item>
				<el-form-item prop="playlet_number" label="" size="medium">
					<div class="d-flex flex-row">
						<el-select class="d-flex w-50" clearable v-model="dataForm.playlet_number" :disabled="dataId?true:false" placeholder="请选择剧集">
							<el-option v-for="(item,index) in allEpisodeList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
					</div>
				</el-form-item>
				<!-- <el-form-item prop="follow_playlet_id" v-if="dataForm.playlet_id"  label="后续短剧" size="medium">
					<div class="d-flex flex-row " style="align-items: center;">
						<el-select class="d-flex w-50" clearable v-model="dataForm.follow_playlet_id" :disabled="diyshow_follow && dataId?true:false" placeholder="请选择推广短剧"  @change="episodeFn2(false)">
							<el-option v-for="(item,index) in playletList2" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
						<div  v-if="!diyshow_switch" style="margin-left: 20px;position: relative;">
							<el-switch 
								v-model="dataForm.is_open"
								:disabled="dataForm.follow_playlet_id == ''"
								active-text="已开启"
								inactive-text="未开启">
							</el-switch>
							<div style="position: absolute;top: 24px;font-size: 11px;color: red;">注意：开启后不能关闭！！</div>
						</div>
						
					</div>
				</el-form-item> -->
				<el-form-item prop="playlet_number_num" label="付费集数" size="medium">
					<div class="d-flex flex-row">
						<div class="d-flex flex-shrink a-center j-center input_prepend">
							<div class="d-flex">第</div>
						</div>
						<el-input-number class="inputNum" v-model="dataForm.playlet_number_num" controls-position="right" :min="0" :max="999"
						@keydown.native="(e)=>(dataForm.playlet_number_num=numNoPoint(e.target.value))"
						@keyup.native="(e)=>(dataForm.playlet_number_num=numNoPoint(e.target.value))"
						clearable></el-input-number>
						<div class="d-flex flex-shrink a-center j-center input_append">
							<div class="d-flex">集起</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item prop="playlet_number_num_pay" label="单集价格" size="medium">
					<div class="d-flex flex-row">
						<el-input-number class="inputNum" v-model="dataForm.playlet_number_num_pay" controls-position="right" :min="0" :max="99999"
						@keydown.native="(e)=>(dataForm.playlet_number_num_pay=numNoPoint(e.target.value))"
						@keyup.native="(e)=>(dataForm.playlet_number_num_pay=numNoPoint(e.target.value))"
						clearable></el-input-number>
						<div class="d-flex flex-shrink a-center j-center input_append">
							<div class="d-flex">追剧币</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item prop="recharge_template_type" label="充值模板" size="medium">
					<el-radio-group v-model="dataForm.recharge_template_type"  @input="getTempleteFn(dataForm,1,2)">
						<el-radio-button label="1">默认充值模板</el-radio-button>
						<el-radio-button label="2">自定义模板</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="dataForm.recharge_template_type==2" prop="recharge_template_id" label="首充模板" size="medium">
					<el-select filterable :popper-append-to-body="false" filterable :loading="templeteListLoading" remote clearable v-model="dataForm.recharge_template_id" placeholder="请选择">
						<el-option v-for="(item,index) in templeteList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="dataForm.recharge_template_type==2" prop="assistant_recharge_template_id" label="复充模板" size="medium">
					<el-select filterable :popper-append-to-body="false" filterable :loading="templeteListLoading" remote clearable v-model="dataForm.assistant_recharge_template_id" placeholder="请选择" >
						<el-option v-for="(item,index) in templeteList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="dataForm.recharge_template_type==2" prop="retention_template_id" label="挽留模板">
					<el-select filterable clearable :loading="templeteListLoading" remote v-model="dataForm.retention_template_id" placeholder="请选择">
						<el-option v-for="(item,index) in templeteList2" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
					</el-select>
				</el-form-item>
			</template>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	import {
		debounce
	} from 'lodash'
	import {
		numNoPoint
	} from '@/libs/validate'
	import schema from 'async-validator'
	export default {
		data() {
			return {
				numNoPoint,
				userType:[{
					label:'普通用户',
					value:1
				},{
					label:'星图用户',
					value:2
				}],
				diyshow_follow:false,
				diyshow_switch:false,
				diytype:2,
				templeteListLoading:false,
				dataId:null,
				platformId:[],
				appletList:[],
				playletList:[],
				playletList2:[],
				allEpisodeList:[],
				templeteList:[],
				templeteList2:[],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				noPlaylet: false,//是否显示没有短剧
				roleList: [],
				roleIdListDefault: [],
				diyad_account:'',
				diyname:null,
				dataForm: {

					name: '', //推广链接名称	
					spread_platform_id:'',//投放平台id
					applet_id:'',//小程序id
					user_type:1,//用户类型
					playlet_id:'',//短剧id
					follow_playlet_id:'',//后续短剧
					is_open:false,
					playlet_number:'',//集数数字
					playlet_number_num:'',//收费集数
					playlet_number_num_pay:'',//单集价格
					recharge_template_type:1,//充值模板类型 1：默认充值模板，2：自定义充值模板
					recharge_template_id:'',//自定义充值模板--首充模板id
					assistant_recharge_template_id:'',//自定义充值模板--复充模板id
					operation_mode:1,
					ad_account:''
				}
			}
		},
		created() {},
		computed: {
			dataRule() {
				return {
					name: [{
							required: true,
							message: '名称不能为空!',
							trigger: ['blur','change']
						}
					],
					spread_platform_id: [{
						required: true,
						message: '投放平台不能为空！',
						trigger: ['blur','change']
					}],
					user_type: [{
						required: true,
						message: '用户类型不能为空！',
						trigger: ['blur','change']
					}],
					applet_id: [{
						required: true,
						message: '请选择小程序！',
						trigger: ['blur','change']
					}],
					playlet_id: [{
						required: true,
						message: '请选择短剧！',
						trigger: ['blur','change']
					}],
					playlet_number: [{
						required: true,
						message: '请选择剧集！',
						trigger: ['blur','change']
					}],
					playlet_number_num: [{
						required: true,
						message: '收费集数不能为空！',
						trigger: ['blur','change']
					}],
					playlet_number_num_pay: [{
						required: true,
						message: '单集价格不能为空！',
						trigger: ['blur','change']
					}],
					recharge_template_type: [{
						required: true,
						message: '充值模板不能为空！',
						trigger: ['blur','change']
					}],
					recharge_template_id: [{
						required: true,
						message: '首充模板不能为空！',
						trigger: ['blur','change']
					}],
					assistant_recharge_template_id: [{
						required: true,
						message: '复充模板不能为空！',
						trigger: ['blur','change']
					}]
				}
			}
		},
		watch:{
		},
		methods: {
			closeFn(){
				this.$refs.dataForm.resetFields();
				this.dataForm.recharge_template_type = 1;
				this.dataForm.recharge_template_id = '';
			},
			//投放平台列表
			async getPlatformFn(){
				const platformIdRes = await this.$axios.get('/api/common/platform');
				console.log(platformIdRes);
				if(Array.isArray(platformIdRes)){
					if(platformIdRes.length){
						this.platformId = platformIdRes;
						return;
					}
				}
				this.platformId = [];
			},
			selectSpread(e){
				console.log(229,e,this.dataForm.spread_platform_id)
				this.dataForm.applet_id = '';
				this.dataForm.playlet_id = '';
				this.dataForm.playlet_number = '';
			},
			//小程序列表
			async getAppletFn(init=true){
				console.log(230,this.dataForm.spread_platform_id);
				const appletRes = await this.$axios.get(`/api/delivery/company/getApplet/${this.dataForm.spread_platform_id}`);
				console.log(232,appletRes);
				if(Array.isArray(appletRes)){
					if(appletRes.length){
						this.appletList = appletRes;
						if(!init){
							this.getPlayletFn(false);
						}
						return;
					}
				}
				this.appletList = [];
			},
			//小程序所绑定的短剧列表
			async getPlayletFn(init=true){
				this.noPlaylet = false;
				console.log(66666,init)
				if(init){
					this.dataForm.playlet_id = '';
					this.dataForm.playlet_number = '';
				}
				console.log(283,this.dataForm.applet_id,this.appletList)
				try {
					this.appletList.forEach((item,index)=>{
					if(item.value ==this.dataForm.applet_id){
						this.diytype = item.type
						if(item.type == 1){
							this.dataForm.operation_mode = 1
						}
						throw false
					}
					console.log(270,index)
				})
				} catch (error) {}
			
				// this.dataForm.operation_mode = 1
				if(!this.dataForm.applet_id) return;
				const playletRes = await this.$axios.get(`/api/delivery/applet/playletList/${this.dataForm.applet_id}`);
				
				if(Array.isArray(playletRes)){
					if(playletRes.length){
						this.playletList = playletRes;
						if(!init){
							this.episodeFn();
						}
						return;
					}
				}
				this.noPlaylet = true;
				this.playletList = [];
				this.playletList2 = [];
			
				this.clearPlayletFn();
			
			},
			//获取剧集集数
			async episodeFn(init=true){
				console.log(9999999,init)
				let arr = this.playletList;
				let num = this.dataForm.playlet_id
				this.playletList2 = arr.filter(item=>item.value!=num)
				// if(this.dataForm.playlet_id !="" && this.dataForm.playlet_id == this.dataForm.follow_playlet_id){
				// 	this.dataForm.follow_playlet_id = '';
				// }
			
				if(!init){
					this.dataForm.playlet_number = '';
					this.dataForm.follow_playlet_id = '';
					this.dataForm.is_open = false;
				}
				
				if(!this.dataForm.playlet_id) return;
				const episodeRes = await this.$axios.get(`/api/delivery/playlet/episodes/${this.dataForm.playlet_id}`);
				console.log(episodeRes);
				if(Array.isArray(episodeRes)){
					if(episodeRes.length){
						this.allEpisodeList = episodeRes;
						return;
					}
				}
				this.allEpisodeList = [];
			},
			episodeFn2(){
				this.dataForm.is_open = false
			},
		
			//充值模板列表
			async getTempleteFn(row,type,type2){
				if(!row.applet_id){
					return this.$message({
						message: '缺少小程序id',
						type: 'error',
						duration: 1200
					})	
				}
				if(type2){
					 this.getTempleteFn(row,2)
				}
				this.templeteListLoading = true;
				const templeteListRes = await this.$axios.get(`/api/delivery/dataSpread/getTemplete/${type}`);
				this.templeteListLoading = false;
				if(Array.isArray(templeteListRes)){
					if(templeteListRes.length){
						this[ type == 1 ? 'templeteList' : 'templeteList2'] = templeteListRes;
						console.log(this[ type == 1 ? 'templeteList' : 'templeteList2']);
						return;
					}
				}
				this[ type == 1 ? 'templeteList' : 'templeteList2'] = [];
				
			},
			clearCompanyFn(){
				this.dataForm.applet_id = '';
				this.dataForm.playlet_id = '';
				this.dataForm.playlet_number = '';
				this.dataForm.playlet_number_num = '';
				this.dataForm.playlet_number_num_pay = '';
				this.dataForm.recharge_template_type = 1;
				this.dataForm.recharge_template_id = 1;
			},
			clearPlayletFn(){
				this.dataForm.playlet_id = '';
				this.dataForm.playlet_number = '';
				this.dataForm.playlet_number_num = '';
				this.dataForm.playlet_number_num_pay = '';
				this.dataForm.recharge_template_type = 1;
				this.dataForm.recharge_template_id = 1;
			},
			init() {
				this.visible = true;
				this.dataForm.applet_id='';
				this.dataForm.operation_mode=1;
				this.diyshow_switch = false;
				this.dataForm ={
					name: '', //推广链接名称	
					spread_platform_id:'',//投放平台id
					company_id:'',//公司id
					applet_id:'',//小程序id
					user_type:1,//用户类型
					is_open:false,
					playlet_id:'',//短剧id
					follow_playlet_id:'',
					playlet_number:'',//集数数字
					playlet_number_num:'',//付费集数
					playlet_number_num_pay:'',//单集价格
					recharge_template_type:1,//充值模板类型 1：默认充值模板，2：自定义充值模板
					recharge_template_id:'',//自定义充值模板--首充模板id
					assistant_recharge_template_id:'',//自定义充值模板--复充模板id
					operation_mode:1,
					ad_account :''
				}
			},
			update(row) {
				console.log(356,row)
				this.diyad_account = row.ad_account
				this.dataForm = {
							name: '', //推广链接名称	
							spread_platform_id:'',//投放平台id
							applet_id:'',//小程序id
							user_type:1,//用户类型
							playlet_id:'',//短剧id
							follow_playlet_id:'',
							is_open:false,
							playlet_number:'',//集数数字
							playlet_number_num:'',//付费集数
							playlet_number_num_pay:'',//单集价格
							recharge_template_type:1,//充值模板类型 1：默认充值模板，2：自定义充值模板
							recharge_template_id:'',//自定义充值模板--首充模板id
							assistant_recharge_template_id:'',//自定义充值模板--复充模板id
							operation_mode:1,
							ad_account:''
						}
				this.diyshow_switch = row.is_open == 1 ? false : true
				this.diyshow_follow = row.follow_playlet_id =='' ? false : true
				this.visible = true;
				this.getPlatformFn();
				this.$nextTick(() => {
					// this.$refs.dataForm.resetFields();
					this.dataForm = JSON.parse(JSON.stringify(row));
					if(this.diyname){
						this.dataForm.ad_account = ''
						this.diyshow_switch = false
					}
					this.getAppletFn(false);
					console.log(363,this.dataForm);
					this.getTempleteFn(row,1,2);
				})
			},
			accountBindHandleSetter(row){
				console.log(442,row.ad_account)
				this.$axios.post(`/api/delivery/dataSpread/accountBind/${row.ad_account}/1`, {}).then(res => {
						console.log(533)
	
						// this.getTableList(true);
						this.$message({
							message: this.$t('解绑成功'),
							type: 'success',
							duration: 1500,
							onClose: () => {
							}
						})
						console.log(542)
				}).catch(() => {})
			},

			dataFormSubmit(){
				console.log(475,this.dataForm)
				console.log(474,this.dataForm.is_open ? 2 : 1)
				this.dataForm.ad_account  =  this.dataForm?.ad_account.split(" ").join("");
				this.dataForm.is_open = this.dataForm.is_open ? 2 : 1  
				
				this.$axios.post(this.dataId?`/api/delivery/dataSpread/update/${this.dataId}`:'/api/delivery/dataSpread/create', this.dataForm).then(res => {
					console.log(414,res)
					if(res && res?.code == 410){
						this.$confirm(res.message, {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
						}).then(() => {
							console.log(440,this.dataForm)
							this.accountBindHandleSetter(this.dataForm)
							this.dataForm.is_open = false;
						}).catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});          
						});
					}else{
						console.log(453,this.diyname)
						let diymessage = this.diyname ? '复制成功' : this.dataId? '修改成功' : '新建成功'
						this.dataForm.is_open = false;
						this.$message({
							message: this.$t(diymessage),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}
				
					
				}).catch((err) => {
					console.log(512,err)
					this.dataForm.is_open = false;
				})
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(this.dataForm);
					if(this.diyname == this.dataForm.name){
						
						console.log(495)
						this.$confirm('链接名称尚未修改，是否继续提交')
						.then(_ => {
							this.dataFormSubmit()
						})
						.catch(_ => { });
					
					}else{
						this.dataFormSubmit()
					}
					})
			}, 1000, {
				leading: true,
				trailing: false
			})

		}
	}
</script>

<style lang="scss" scoped>
	.form{
		width: 540px;
	}
	.input_prepend{
		border-right: 0px!important;
		border-top-right-radius: 0px!important;
		border-bottom-right-radius: 0px!important;
		padding: 0 30px;
	}
	.input_append{
		border-left: 0px!important;
		border-top-left-radius: 0px!important;
		border-bottom-left-radius: 0px!important;
		padding: 0 40px;
	}
	.input_prepend,.input_append{
		background-color: #F5F7FA;
		color: #909399;
		vertical-align: middle;
		position: relative;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		width: 1px;
		white-space: nowrap;
	}
	.inputNum{
		width: auto;
		flex: 1;
	}
	:deep(.inputNum .el-input__inner){
		border-radius: 0px;
		height: 38px;
	}
</style>